package org.bobo.utils.job;


import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class QuartzBiz {

    @Autowired
    private Scheduler scheduler;


    /**
     * @param jobClassName
     * @param cronExpression
     * @param jobName
     * @param type
     * @param onlyParam      用来查询的唯一参数值
     */
    public void addJob(String jobClassName, String cronExpression, String jobName, String type, String onlyParam) {
        try {
            // 启动调度器
            scheduler.start();
            // 构建job信息
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("type", type);
            jobDataMap.put("onlyParam", onlyParam);
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobName).usingJobData(jobDataMap).build();
            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("创建定时任务成功");
        } catch (SchedulerException e) {
            e.printStackTrace();
//            throw new AdminServiceException(new ServiceExceptionDefinition(12345, "创建定时任务失败"));
            log.info("创建定时任务失败");
        } catch (Exception e) {
//            throw new AdminServiceException(new ServiceExceptionDefinition(12345, "后台找不到该类名：" + jobClassName));
            log.info("后台找不到该类名");
        }

    }
    /**
     * @param jobName
     */
    public void delJob(String jobName) {
        try {
            // 启动调度器
            scheduler.start();

            scheduler.deleteJob(new JobKey(jobName));
            log.info("删除定时任务成功");
        } catch (SchedulerException e) {
            e.printStackTrace();
//            throw new AdminServiceException(new ServiceExceptionDefinition(12345, "创建定时任务失败"));
            log.info("删除定时任务失败");
        } catch (Exception e) {
//            throw new AdminServiceException(new ServiceExceptionDefinition(12345, "后台找不到该类名：" + jobClassName));
            log.info("后台找不到该类名");
        }
    }

    private static Job getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
//        //Test为要实例化的类名
//        Constructor constructor = class1 .getConstructor(String.class);
//        //String.class是Test类构造函数（public 修饰不可省略）的参数
//        Object obj=  (Object ) constructor.newInstance("1");
        return (Job) class1.newInstance();
    }
}